# Windows AMD64 Client Build Script
# Used to build Flutter client on Windows systems

# ============================================================
# Comprehensive Encoding Fix for Chinese Characters
# ============================================================

# Set console code page to UTF-8
chcp 65001 > $null

# Set PowerShell output encoding
$OutputEncoding = [System.Text.Encoding]::UTF8

# Set console input/output encoding
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8

# Set default encoding for Out-File and other cmdlets
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
$PSDefaultParameterValues['Get-Content:Encoding'] = 'utf8'

# Set environment variables for encoding
$env:PYTHONIOENCODING = "utf-8"

# Clear console to ensure clean start
Clear-Host

# Test encoding
Write-Host "=== Windows AMD64 Client Build Script ===" -ForegroundColor Green
Write-Host "Encoding test: 中文测试 - English test" -ForegroundColor Yellow
Write-Host ""

# ============================================================
# Main Build Script
# ============================================================

Write-Host "================================================================================" -ForegroundColor White
Write-Host "🪟 Windows AMD64 Client Build Script" -ForegroundColor Cyan
Write-Host "================================================================================" -ForegroundColor White
Write-Host ""

# Get script directory
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location -Path $ScriptDir

Write-Host "📋 Checking build environment..." -ForegroundColor Yellow
Write-Host ""

# Check Flutter
try {
    $FlutterPath = Get-Command "flutter" -ErrorAction Stop
    Write-Host "✅ Flutter found at: $($FlutterPath.Source)" -ForegroundColor Green
} catch {
    Write-Host "❌ Flutter is not installed or not in PATH" -ForegroundColor Red
    Write-Host "   Please install Flutter first: https://flutter.dev/docs/get-started/install/windows" -ForegroundColor Gray
    Pause
    Exit 1
}

Write-Host "✅ Flutter version:" -ForegroundColor Green
flutter --version | Select-String "Flutter"
Write-Host ""

# Check Go
try {
    $GoPath = Get-Command "go" -ErrorAction Stop
    Write-Host "✅ Go found at: $($GoPath.Source)" -ForegroundColor Green
} catch {
    Write-Host "❌ Go is not installed or not in PATH" -ForegroundColor Red
    Write-Host "   Please install Go first: https://golang.org/dl/" -ForegroundColor Gray
    Pause
    Exit 1
}

$GoVersion = go version
Write-Host "✅ Go version: $GoVersion" -ForegroundColor Green
Write-Host ""

# Check C compiler (required for CGO)
Write-Host "🔍 Checking C compiler (required for CGO)..." -ForegroundColor Yellow
$CompilerFound = $false
$UseGcc = $false

# Check for GCC
try {
    $GccPath = Get-Command "gcc" -ErrorAction Stop
    Write-Host "✅ GCC found at: $($GccPath.Source)" -ForegroundColor Green
    $CompilerFound = $true
    $UseGcc = $true
} catch {
    # Check for GCC in common locations
    $CommonGccPaths = @(
        "C:\TDM-GCC-64\bin\gcc.exe",
        "C:\MinGW\bin\gcc.exe",
        "C:\msys64\mingw64\bin\gcc.exe"
    )
    
    foreach ($Path in $CommonGccPaths) {
        if (Test-Path $Path) {
            Write-Host "✅ GCC found at: $Path" -ForegroundColor Green
            # Add the directory to PATH
            $GccDir = Split-Path -Parent $Path
            $env:PATH = "$GccDir;$env:PATH"
            Write-Host "   Added $GccDir to PATH" -ForegroundColor Gray
            $CompilerFound = $true
            $UseGcc = $true
            break
        }
    }
    
    if (-not $CompilerFound) {
        # Check for Visual Studio C++ compiler (cl.exe) in common locations
        try {
            $ClPath = Get-Command "cl.exe" -ErrorAction Stop
            Write-Host "✅ Visual Studio C++ compiler (cl.exe) found at: $($ClPath.Source)" -ForegroundColor Green
            $CompilerFound = $true
        } catch {
            # Try to find Visual Studio installation and check for cl.exe there
            $VsWherePath = "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
            if (Test-Path $VsWherePath) {
                try {
                    $ClPath = & $VsWherePath -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -find '**\bin\Hostx64\x64\cl.exe' 2>$null
                    if ($ClPath) {
                        Write-Host "✅ Visual Studio C++ compiler (cl.exe) found at: $ClPath" -ForegroundColor Green
                        $CompilerFound = $true
                    }
                } catch {
                    # Ignore errors from vswhere
                }
            }
        }
    }
}

if (-not $CompilerFound) {
    Write-Host "⚠️  No C compiler found" -ForegroundColor Yellow
    Write-Host "   CGO-enabled builds require a C compiler:" -ForegroundColor Gray
    Write-Host "   Option 1: Install MinGW-w64 or MSYS2 with GCC" -ForegroundColor Gray
    Write-Host "   Option 2: Install Visual Studio with C++ build tools" -ForegroundColor Gray
    Write-Host ""
    Write-Host "   If you continue without a C compiler, the Go tunnel library compilation will fail." -ForegroundColor Yellow
    Write-Host ""
    $Continue = Read-Host "Continue anyway? (y/N)"
    if ($Continue -ne "y" -and $Continue -ne "Y") {
        Exit 1
    }
}
Write-Host ""

# Check NuGet
Write-Host "🔍 Checking NuGet..." -ForegroundColor Yellow
$NuGetFound = $false

# Check if nuget is in PATH
try {
    $NuGetPath = Get-Command "nuget" -ErrorAction Stop
    Write-Host "✅ NuGet found at: $($NuGetPath.Source)" -ForegroundColor Green
    $NuGetFound = $true
} catch {
    # Check for NuGet in common locations
    $CommonNuGetPaths = @(
        "D:\tools\nuget.exe",
        "C:\Program Files (x86)\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\NuGet.exe",
        "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\NuGet.exe"
    )
    
    foreach ($Path in $CommonNuGetPaths) {
        if (Test-Path $Path) {
            Write-Host "✅ NuGet found at: $Path" -ForegroundColor Green
            # Add the directory to PATH
            $NuGetDir = Split-Path -Parent $Path
            $env:PATH = "$NuGetDir;$env:PATH"
            Write-Host "   Added $NuGetDir to PATH" -ForegroundColor Gray
            $NuGetFound = $true
            break
        }
    }
}

if (-not $NuGetFound) {
    Write-Host "⚠️  NuGet not found" -ForegroundColor Yellow
    Write-Host "   NuGet is required for Flutter Windows builds" -ForegroundColor Gray
    Write-Host "   Please install NuGet or ensure it's in your PATH" -ForegroundColor Gray
    Write-Host ""
    $Continue = Read-Host "Continue anyway? (y/N)"
    if ($Continue -ne "y" -and $Continue -ne "Y") {
        Exit 1
    }
}
Write-Host ""

# Check Visual Studio (MSBuild)
$VSFound = $false
try {
    $ClPath = Get-Command "cl.exe" -ErrorAction Stop
    $VSFound = $true
    Write-Host "✅ Visual Studio C++ compiler found at: $($ClPath.Source)" -ForegroundColor Green
} catch {
    # Try to find Visual Studio installation
    $VsWherePath = "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
    if (Test-Path $VsWherePath) {
        try {
            $VsInfo = & $VsWherePath -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property displayName 2>$null
            if ($VsInfo) {
                Write-Host "✅ Visual Studio with C++ tools found:" -ForegroundColor Green
                $VsInfo | ForEach-Object { Write-Host "      $_" -ForegroundColor Gray }
                $VSFound = $true
            }
        } catch {
            # Ignore errors from vswhere
        }
    }
    
    if (-not $VSFound) {
        Write-Host "⚠️  Warning: Visual Studio C++ compiler not detected in PATH" -ForegroundColor Yellow
        Write-Host "   Flutter Windows build requires Visual Studio 2022 and C++ desktop development tools" -ForegroundColor Gray
        Write-Host "   Download: https://visualstudio.microsoft.com/" -ForegroundColor Gray
        Write-Host ""
        Write-Host "   If already installed, run this script in 'x64 Native Tools Command Prompt for VS 2022'" -ForegroundColor Gray
        Write-Host ""
        $Continue = Read-Host "Continue? (y/N)"
        if ($Continue -ne "y" -and $Continue -ne "Y") {
            Exit 1
        }
    }
}
Write-Host ""

Write-Host "🖨️  Current OS: Windows" -ForegroundColor Yellow
Write-Host ""

# ============================================================
# Step 1: Compile Go Tunnel Library (Windows AMD64)
# ============================================================

Write-Host "================================================================================" -ForegroundColor White
Write-Host "🔨 Step 1/3: Compile Go Tunnel Library (Windows AMD64)" -ForegroundColor Cyan
Write-Host "================================================================================" -ForegroundColor White
Write-Host ""

Set-Location -Path "$ScriptDir\go_tunnel"

# Clean Go build cache and temporary files
Write-Host "🗑️  Cleaning Go build cache and temporary files..." -ForegroundColor Yellow
go clean -cache 2>$null
Get-ChildItem "*.o", "*.a", "*.so", "*.dll", "*.dylib" -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
Write-Host ""

# Create output directory
$OutputDir = "..\assets\libs"
if (!(Test-Path $OutputDir)) {
    New-Item -ItemType Directory -Path $OutputDir | Out-Null
}

$OutputFile = "$OutputDir\simple_tunnel_windows_amd64.dll"

# Clean old files
if (Test-Path $OutputFile) {
    Write-Host "🗑️  Cleaning old DLL files..." -ForegroundColor Yellow
    Remove-Item $OutputFile -Force
    $HeaderFile = $OutputFile -replace '\.dll$', '.h'
    if (Test-Path $HeaderFile) {
        Remove-Item $HeaderFile -Force
    }
}

Write-Host "✅ Compiling directly on Windows system..." -ForegroundColor Green
Write-Host ""

# Set environment variables properly for PowerShell
$env:GOOS = "windows"
$env:GOARCH = "amd64"
$env:CGO_ENABLED = "1"

# If we found GCC, set CC to gcc; otherwise use cl.exe
if ($UseGcc) {
    $env:CC = "gcc"
    Write-Host "🔧 Using GCC as C compiler" -ForegroundColor Yellow
} else {
    $env:CC = "cl.exe"
    Write-Host "🔧 Using Visual Studio cl.exe as C compiler" -ForegroundColor Yellow
}

Write-Host "🔍 Build parameters:" -ForegroundColor Yellow
Write-Host "   GOOS=$env:GOOS" -ForegroundColor Gray
Write-Host "   GOARCH=$env:GOARCH" -ForegroundColor Gray
Write-Host "   CGO_ENABLED=$env:CGO_ENABLED" -ForegroundColor Gray
Write-Host "   CC=$env:CC" -ForegroundColor Gray
Write-Host ""

# Compile Go DLL - Only include files relevant to Windows platform
Write-Host "Compiling Go DLL..." -ForegroundColor Yellow
# Get only the Go files that are relevant for Windows platform
$GoFiles = @(
    "connection_pool.go",
    "http2_client.go", 
    "http2_connection_pool.go",
    "http_protocol.go",
    "interfaces.go",
    "tunnel_connection_pool.go",
    "tunnel_manager.go"
)

# Verify all required files exist
$MissingFiles = @()
foreach ($file in $GoFiles) {
    if (-not (Test-Path $file)) {
        $MissingFiles += $file
    }
}

if ($MissingFiles.Count -gt 0) {
    Write-Host "❌ Missing required Go files:" -ForegroundColor Red
    $MissingFiles | ForEach-Object { Write-Host "   $_" -ForegroundColor Red }
    Set-Location -Path $ScriptDir
    Pause
    Exit 1
}

$GoFileList = $GoFiles -join " "
Write-Host "Running: go build -a -buildmode=c-shared -ldflags=""-s -w"" -o ""$OutputFile"" $GoFileList" -ForegroundColor Gray

# Run build with verbose output to see any errors
$BuildOutput = go build -v -a -buildmode=c-shared -ldflags="-s -w" -o $OutputFile $GoFiles 2>&1
$BuildExitCode = $LASTEXITCODE

if ($BuildExitCode -ne 0) {
    Write-Host ""
    Write-Host "❌ Windows DLL compilation failed" -ForegroundColor Red
    Write-Host "Build output:" -ForegroundColor Yellow
    $BuildOutput | ForEach-Object { Write-Host "   $_" -ForegroundColor Gray }
    Set-Location -Path $ScriptDir
    Pause
    Exit 1
}

Write-Host ""
Write-Host "✅ Windows DLL compiled successfully!" -ForegroundColor Green
if (Test-Path $OutputFile) {
    $FileInfo = Get-Item $OutputFile
    Write-Host "   File: $($FileInfo.FullName)" -ForegroundColor Gray
    Write-Host "   Size: $($FileInfo.Length) bytes" -ForegroundColor Gray
}
Write-Host ""

Set-Location -Path $ScriptDir

Write-Host ""

# ============================================================
# Step 2: Flutter Dependencies Installation
# ============================================================

Write-Host "================================================================================" -ForegroundColor White
Write-Host "📦 Step 2/3: Installing Flutter Dependencies" -ForegroundColor Cyan
Write-Host "================================================================================" -ForegroundColor White
Write-Host ""

Write-Host "📥 Getting Flutter dependencies..." -ForegroundColor Yellow
$PubGetOutput = flutter pub get 2>&1
$PubGetExitCode = $LASTEXITCODE

if ($PubGetExitCode -ne 0) {
    Write-Host ""
    Write-Host "❌ Flutter dependencies installation failed" -ForegroundColor Red
    Write-Host "Build output:" -ForegroundColor Yellow
    $PubGetOutput | ForEach-Object { Write-Host "   $_" -ForegroundColor Gray }
    Pause
    Exit 1
}

Write-Host ""
Write-Host "✅ Dependencies installation completed" -ForegroundColor Green
Write-Host ""

# ============================================================
# Step 3: Build Flutter Windows Application
# ============================================================

Write-Host "================================================================================" -ForegroundColor White
Write-Host "🏗️  Step 3/3: Building Flutter Windows Application" -ForegroundColor Cyan
Write-Host "================================================================================" -ForegroundColor White
Write-Host ""

Write-Host "🔨 Starting Windows Release build..." -ForegroundColor Yellow
Write-Host ""

# Clean previous builds
$BuildDir = "build\windows"
if (Test-Path $BuildDir) {
    Write-Host "🗑️  Cleaning old build files..." -ForegroundColor Yellow
    Remove-Item $BuildDir -Recurse -Force
}

# Build Windows application
Write-Host "Building Windows application..." -ForegroundColor Yellow
$BuildOutput = flutter build windows --release 2>&1
$BuildExitCode = $LASTEXITCODE

if ($BuildExitCode -ne 0) {
    Write-Host ""
    Write-Host "❌ Flutter Windows application build failed" -ForegroundColor Red
    Write-Host ""
    
    # Check if the error is related to NuGet
    $NuGetError = $BuildOutput -match "Nuget.exe not found"
    if ($NuGetError) {
        Write-Host "💡 NuGet.exe not found. This is a common issue with Flutter Windows builds." -ForegroundColor Yellow
        Write-Host "   Possible solutions:" -ForegroundColor Gray
        Write-Host "   1. Install Visual Studio with C++ desktop development tools (includes NuGet)" -ForegroundColor Gray
        Write-Host "   2. Install NuGet command line tool:" -ForegroundColor Gray
        Write-Host "      - Download from https://www.nuget.org/downloads" -ForegroundColor Gray
        Write-Host "      - Place nuget.exe in your PATH" -ForegroundColor Gray
        Write-Host "   3. Run this script from 'x64 Native Tools Command Prompt for VS 2022'" -ForegroundColor Gray
        Write-Host ""
    }
    
    Write-Host "💡 Common issues:" -ForegroundColor Yellow
    Write-Host "   1. Ensure Visual Studio 2022 and C++ desktop development tools are installed" -ForegroundColor Gray
    Write-Host "   2. Run this script in 'x64 Native Tools Command Prompt for VS 2022'" -ForegroundColor Gray
    Write-Host "   3. Run flutter doctor to check environment" -ForegroundColor Gray
    Write-Host ""
    
    Write-Host "Build output:" -ForegroundColor Yellow
    $BuildOutput | ForEach-Object { Write-Host "   $_" -ForegroundColor Gray }
    Write-Host ""
    Pause
    Exit 1
}

Write-Host ""
Write-Host "✅ Flutter Windows application built successfully!" -ForegroundColor Green
Write-Host ""

# Show output directory
$BuildOutput = "build\windows\x64\runner\Release"
if (Test-Path $BuildOutput) {
    Write-Host "📁 Build output directory:" -ForegroundColor Yellow
    Write-Host "   $(Get-Location)\$BuildOutput" -ForegroundColor Gray
    Write-Host ""
    
    # Show executable file
    $Executable = "$BuildOutput\internal_net_bridge.exe"
    if (Test-Path $Executable) {
        $FileInfo = Get-Item $Executable
        Write-Host "🚀 Executable file:" -ForegroundColor Cyan
        Write-Host "   internal_net_bridge.exe ($($FileInfo.Length) bytes)" -ForegroundColor Gray
        Write-Host ""
    }
    
    # Check if DLL was copied
    $DllPath = "$BuildOutput\data\flutter_assets\assets\libs\simple_tunnel_windows_amd64.dll"
    if (Test-Path $DllPath) {
        Write-Host "✅ Go Tunnel DLL included in application" -ForegroundColor Green
    } else {
        Write-Host "⚠️  Warning: Go Tunnel DLL not found, application may not work properly" -ForegroundColor Yellow
    }
    Write-Host ""
    
    # List main files
    Write-Host "📦 Main file list:" -ForegroundColor Yellow
    Get-ChildItem $BuildOutput -File | ForEach-Object { Write-Host "   $($_.Name)" -ForegroundColor Gray }
    Write-Host ""
}

# ============================================================
# Build Completion Summary
# ============================================================

Write-Host "================================================================================" -ForegroundColor White
Write-Host "🎉 Windows AMD64 Client Build Completed!" -ForegroundColor Cyan
Write-Host "================================================================================" -ForegroundColor White
Write-Host ""
Write-Host "📍 Output location:" -ForegroundColor Yellow
Write-Host "   $(Get-Location)\$BuildOutput" -ForegroundColor Gray
Write-Host ""
Write-Host "📦 Packaging suggestions:" -ForegroundColor Yellow
Write-Host "   1. Package entire Release directory as ZIP file:" -ForegroundColor Gray
Write-Host "      Compress-Archive -Path '$BuildOutput' -DestinationPath 'internal_net_bridge_windows_amd64.zip'" -ForegroundColor Gray
Write-Host ""
Write-Host "   2. Or use NSIS/Inno Setup to create installer" -ForegroundColor Gray
Write-Host ""
Write-Host "🚀 Testing method:" -ForegroundColor Yellow
Write-Host "   cd $BuildOutput" -ForegroundColor Gray
Write-Host "   .\internal_net_bridge.exe" -ForegroundColor Gray
Write-Host ""
Write-Host "⚠️  Notes:" -ForegroundColor Yellow
Write-Host "   1. Ensure target system has Visual C++ Redistributable installed" -ForegroundColor Gray
Write-Host "      Download: https://aka.ms/vs/17/release/vc_redist.x64.exe" -ForegroundColor Gray
Write-Host "   2. First run may require administrator privileges" -ForegroundColor Gray
Write-Host "   3. Firewall may pop up prompts, network access needs to be allowed" -ForegroundColor Gray
Write-Host ""
Write-Host "✨ Done!" -ForegroundColor Green

Pause